import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { 
  NavBar,
  List,
  Avatar,
  Button,
  Tag
} from 'antd-mobile'
import {
  UserOutline,
  MessageOutline,
  StarOutline,
  StarFill
} from 'antd-mobile-icons'
import './concern.css'

// 医生类型定义
interface Doctor {
  id: string
  name: string
  avatar: string
  title: string
  department: string
  hospital: string
  rating: number
  isFollowed: boolean
  lastMessage?: string
  lastMessageTime?: string
}

function Index() {
  const navigate = useNavigate()
  const [doctors, setDoctors] = useState<Doctor[]>([])
  const [loading, setLoading] = useState(true)

  // 从localStorage获取关注的医生数据
  const loadFollowedDoctors = () => {
    const savedDoctors = localStorage.getItem('followedDoctors')
    if (savedDoctors) {
      try {
        const parsedDoctors = JSON.parse(savedDoctors)
        setDoctors(parsedDoctors)
      } catch (error) {
        console.error('解析关注的医生数据失败:', error)
        setDoctors([])
      }
    } else {
      setDoctors([])
    }
    setLoading(false)
  }

  // 监听localStorage变化
  useEffect(() => {
    // 初始加载
    loadFollowedDoctors()

    // 监听storage事件（跨标签页同步）
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'followedDoctors') {
        loadFollowedDoctors()
      }
    }

    // 监听自定义事件（同标签页内同步）
    const handleCustomStorageChange = () => {
      loadFollowedDoctors()
    }

    window.addEventListener('storage', handleStorageChange)
    window.addEventListener('followedDoctorsChanged', handleCustomStorageChange)

    return () => {
      window.removeEventListener('storage', handleStorageChange)
      window.removeEventListener('followedDoctorsChanged', handleCustomStorageChange)
    }
  }, [])

  // 取消关注医生
  const unfollowDoctor = (doctorId: string) => {
    const updatedDoctors = doctors.filter(doctor => doctor.id !== doctorId)
    setDoctors(updatedDoctors)
    localStorage.setItem('followedDoctors', JSON.stringify(updatedDoctors))
  }

  // 跳转到医生详情
  const goToDoctorDetail = (doctor: Doctor) => {
    navigate(`/details?name=${encodeURIComponent(doctor.name)}&avatar=${encodeURIComponent(doctor.avatar)}&title=${encodeURIComponent(doctor.title)}&dept=${encodeURIComponent(doctor.department)}&hospital=${encodeURIComponent(doctor.hospital)}`)
  }

  // 跳转到聊天页面
  const goToChat = (doctor: Doctor) => {
    localStorage.setItem('selectedDoctor', JSON.stringify(doctor))
    navigate('/message')
  }

  // 渲染星级评分
  const renderStars = (rating: number) => {
    const stars = []
    for (let i = 1; i <= 5; i++) {
      stars.push(
        <span key={i} style={{ color: i <= rating ? '#faad14' : '#d9d9d9' }}>
          {i <= rating ? <StarFill /> : <StarOutline />}
        </span>
      )
    }
    return stars
  }

  return (
    <div className="concern-page">
      {/* 顶部导航栏 */}
      <NavBar 
        onBack={() => navigate(-1)}
        right={
          <Button 
            size="small" 
            fill="none"
            onClick={loadFollowedDoctors}
            style={{ color: '#1989fa' }}
          >
            刷新
          </Button>
        }
        style={{ 
          backgroundColor: '#fff',
          borderBottom: '1px solid #f0f0f0'
        }}
      >
        我的医生
      </NavBar>

      {/* 内容区域 */}
      <div className="concern-content">
        {loading ? (
          <div className="loading">加载中...</div>
        ) : doctors.length === 0 ? (
          <div className="empty-state">
            <UserOutline style={{ fontSize: '48px', color: '#ccc' }} />
            <div className="empty-text">暂无关注的医生</div>
            <Button 
              color="primary" 
              fill="outline"
              onClick={() => navigate('/home')}
            >
              去关注医生
            </Button>
          </div>
        ) : (
          <List className="doctor-list">
            {doctors.map((doctor) => (
              <List.Item
                key={doctor.id}
                className="doctor-item"
                onClick={() => goToDoctorDetail(doctor)}
              >
                <div className="doctor-info">
                  <Avatar 
                    src={doctor.avatar}
                    fallback="👨‍⚕️"
                    style={{ '--size': '60px' }}
                  />
                  <div className="doctor-details">
                    <div className="doctor-header">
                      <span className="doctor-name">{doctor.name}</span>
                      <Tag color="primary" fill="outline">
                        {doctor.title}
                      </Tag>
                    </div>
                    <div className="doctor-department">
                      {doctor.department} | {doctor.hospital}
                    </div>
                    <div className="doctor-rating">
                      {renderStars(doctor.rating)}
                      <span className="rating-text">{doctor.rating}</span>
                    </div>
                    {doctor.lastMessage && (
                      <div className="last-message">
                        <span className="message-text">{doctor.lastMessage}</span>
                        <span className="message-time">{doctor.lastMessageTime}</span>
                      </div>
                    )}
                  </div>
                </div>
                <div className="doctor-actions">
                  <Button
                    size="small"
                    color="primary"
                    fill="outline"
                    onClick={(e) => {
                      e.stopPropagation()
                      goToChat(doctor)
                    }}
                  >
                    <MessageOutline />
                    问诊
                  </Button>
                  <Button
                    size="small"
                    color="danger"
                    fill="outline"
                    onClick={(e) => {
                      e.stopPropagation()
                      unfollowDoctor(doctor.id)
                    }}
                  >
                    取消关注
                  </Button>
                </div>
              </List.Item>
            ))}
          </List>
        )}
      </div>
    </div>
  )
}

export default Index
